package com.lc.utils.bean;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.lc.utils.date.DateUtils;

public class BeanUtils {

	@SuppressWarnings("rawtypes")
	public static <T> void bind(T t, Map<String, Object> map) {
		Method[] methods = t.getClass().getMethods();
		for (Method m : methods) {
			if (m.getName().startsWith("set")) {
				String field = m.getName();
				field = field.substring(field.indexOf("set") + 3);
				field = field.toLowerCase().charAt(0) + field.substring(1);
				System.out.println(field);
				if (map.containsKey(field)) {
					Object value = map.get(field);
					Class[] types = m.getParameterTypes();
					value = changeValue(types[0], value);
					try {
						m.invoke(t, value);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				}

			}
		}
	}

	// TODO
	public static Object changeValue(Class<?> type, Object value) {
		if (value == null) {
			return null;
		}

		if (type == String.class) {
			return String.valueOf(value);
		} else if (type == Date.class) {
			if (value instanceof Date) {
				return (Date) value;
			} else {
				return DateUtils.parseToDate(String.valueOf(value));
			}
		} else if (type == List.class) {

		} else {
			String typeName = type.getName();
			if (typeName.equals("int") || type == Integer.class) {
				try {
					Integer result = Integer.parseInt(String.valueOf(value));
					return result;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (typeName.equals("double") || type == Double.class) {
				try {
					Double result = Double.parseDouble(String.valueOf(value));
					return result;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (typeName.equals("long") || type == Long.class) {
				try {
					Long result = Long.parseLong(String.valueOf(value));
					return result;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("not support type." + typeName + " " + value);
				return value;
			}
		}
		return null;
	}

}

